#define PING_COUNT 45; // 心跳包间隔
WiFiClient wifi_client;
String bemfa_server = "bemfa.com"; // "119.91.109.180"
int server_port = 8344;
String uid = "";
String topic = "esp01s";
int ping_second = PING_COUNT;
int bemfa_ntp_second;
extern NTPClient timeClient;
extern void open_relay();
extern void close_relay();
extern void rst();
String open_cmd;                         // from server cmd,打开
String close_cmd;                        // from server cmd,关闭
String rst_cmd;                          // from server cmd,rst
String subscribe_topic_cmd;              // send server cmd,订阅主题
String ping_send = "cmd=0&msg=keep\r\n"; // send server cmd，心跳
String ping_recive = "cmd=0&res=1\r\n";
String tcp_read(int n)
{
    String msg = "";
    if (wifi_client.connected())
    {
        for (int i = 0; i < n; i++)
        {
            if (wifi_client.available())
            {
                break;
            }
            delay(1);
        }
        if (wifi_client.available())
        {
            msg = wifi_client.readString();
        }
    }
    return msg;
}

void bemfa_connect_and_subscribe()
{
    if (wifi_client.connected())
    {
        wifi_client.stop();
    }
    if (wifi_client.connect(bemfa_server.c_str(), server_port) == 0)
    {
        Serial.println("\n巴法云连接失败\n");
        return;
    }
    wifi_client.write(subscribe_topic_cmd.c_str());
    Serial.print("\n巴法云连接成功 "); //
    String msg = tcp_read(100);
    // Serial.print(msg);
    if (msg.compareTo("cmd=1&res=1\r\n") == 0)
    {
        Serial.print("\n巴法云订阅成功 "); //
    }
    else
    {
        Serial.print("\n巴法云订阅失败 "); //
    }
}
void bemfa_setup()
{
    uid = eeprom_get_string(BEMFA_AUTH_INDEX);
    open_cmd = "cmd=2&uid=" + uid + "&topic=" + topic + "&msg=1";
    close_cmd = "cmd=2&uid=" + uid + "&topic=" + topic + "&msg=0";
    rst_cmd = "cmd=2&uid=" + uid + "&topic=" + topic + "&msg=2";
    subscribe_topic_cmd = ("cmd=1&uid=" + uid + "&topic=" + topic + "\r\n");
    bemfa_connect_and_subscribe();
}
String msg;
void bemfa_loop()
{
    // 计数发送心跳包
    if (timeClient.getSeconds() != bemfa_ntp_second)
    {
        // 实际经过秒数
        int tmp = timeClient.getSeconds() - bemfa_ntp_second;
        if (tmp < 0)
        {
            tmp += 60;
        }
        ping_second -= tmp;
        if (ping_second <= 0)
        {
            ping_second = PING_COUNT;
            // 如果连接断开，尝试重连
            if (!wifi_client.connected())
            {
                bemfa_connect_and_subscribe();
            }
            else
            {
                bool ping_is_ok = false;
                for (int i = 0; i < 3; i++)
                {
                    wifi_client.write(ping_send.c_str());
                    msg = tcp_read(100);
                    if (memcmp(msg.c_str(), ping_recive.c_str(), ping_recive.length()) == 0)
                    {
                        ping_is_ok = true;
                        break;
                    }
                    else
                    {
                        delay(100);
                    }
                }
                if (!ping_is_ok)
                {
                    bemfa_connect_and_subscribe();
                }
                else
                {
                    Serial.print("\n巴法云ping成功 "); //
                }
            }
            // Serial.println("\nbemfa ping");
        }
        // Serial.println(ping_second);
        bemfa_ntp_second = timeClient.getSeconds();
    }

    // 接收控制命令
    msg = tcp_read(1);
    if (msg != "")
    {
        Serial.print("\n巴法云命令");
        Serial.print(msg);
        if (memcmp(msg.c_str(), open_cmd.c_str(), open_cmd.length()) == 0)
        {
            open_relay();
        }
        else if (memcmp(msg.c_str(), close_cmd.c_str(), close_cmd.length()) == 0)
        {
            close_relay();
        }
        else if (memcmp(msg.c_str(), rst_cmd.c_str(), rst_cmd.length()) == 0)
        {
            rst();
        }
    }
}